/*
 * @lc app=leetcode.cn id=148 lang=cpp
 *
 * [148] 排序链表
 */

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head && head->next) {
            ListNode *back = split(head);
            ListNode *res = merge(sortList(head), sortList(back));
            return res;
        }
        return head;
    }

    ListNode* split(ListNode* head) {
        ListNode *slow = head, *fast = head, *pre = nullptr;
        while (fast) {
            fast = fast->next;
            if (fast) fast = fast->next;
            pre = slow;
            slow = slow->next;
        }
        pre->next = nullptr;
        return slow;
    }

    ListNode *merge(ListNode *front, ListNode *back) {
        ListNode node; ListNode *cur = &node;
        while (front && back) {
            if (front->val < back->val) {
                cur->next = front; front = front->next;
            }
            else {
                cur->next = back; back = back->next;
            }
            cur = cur->next;
        }
        if (front) cur->next = front;
        if (back) cur->next = back;
        return node.next;
    }

    // 迭代方法
};
// @lc code=end

